<?xml version="1.0" standalone="no" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<html>
<head>
    <script>
        // Browser's height and browser's width
        var BrowseWidth = window.innerWidth;
        var BrowseHeight = window.innerHeight;

        // Constant variables
        var DELAYTIME = 0.5;
        var VELOCITY = 100;
        var ACCELERATION = 100;
        var X_CHANGEBODY = 600;
        var TIMEAPPEARANCE = 3;
        var TIMESTARTMOVE = TIMEAPPEARANCE + 2;
        var DELAY = 1; // The delay between animation stills, in milliseconds. Affects
        // animation smoothness

        // Point class
        function Point(x, y) {
            this.X = x;
            this.Y = y;
            this.toString = function () {
                return this.X + " " + this.Y;
            };
        }

        /**
         * Helpful functions
         */
        /**
         * This function used to calculate distance between 2 points
         */
        function hel_Distance(point1, point2) {
            var distance = Math.sqrt(Math.pow((point1.X - point2.X), 2)
                    + Math.pow((point1.Y - point2.Y), 2));
            return distance;
        }

        /**
         * Dragonfly class
         * @param width, height: browser's width and browser's height
         * @position: The first dragonfly's position
         * @flyId: The Id of dragonfly's tag <g> 
         * @flyLeftBodyId: The id of dragonfly's left body
         * @flyRightBodyId: the id of dragonfly's right body
         */
        function DragonflyObj(width, height, position, flyId, flyLeftBodyId, flyRightBodyId) {
            // Task 1: init path, curPoint, beginPoint, endPoint, domElement,
            // arrayPoints, deltalTime, limitTime
            // init path
            this.arrayPoints = [];
            for (var i = 0; i < 500; i++) {
                var x = Math.floor((Math.random() * width) + 1);
                var y = Math.floor((Math.random() * height) + 1);

                if (x < 20) {
                    x = 20;
                }
                if (x > (BrowseWidth - 20)) {
                    x -= 20;
                }

                if (y < 10) {
                    y = 10;
                }
                if (y > (BrowseHeight - 10)) {
                    y -= 10;
                }


                this.arrayPoints.push(new Point(x, y));
            }

            this.dragonflyID = flyId;
            this.dragonflyLeftBodyID = flyLeftBodyId;
            this.dragonflyRightBodyID = flyRightBodyId;
            this.curPoint = position;
            this.beginPoint = new Point(0, 0);
            this.endPoint = new Point(0, 0);
            this.detalTime = 0;
            this.curIndex = -1;
            this.curS = 0;
            this.limitS = 0;
            this.VectorVelocity = new Point(0, 0);
            this.Vo = 0;
            this.isLeftBody = true;
            this.isAppearance = false;
            this.isMove = false;

            // Task 2: create methods: init() pathToString(), getListPoints(),
            // update(), render()
            /**
             * 
             */
            this.init = function () {
                this.arrayPoints.push(this.curPoint);
                this.curIndex = 0;

                // calculate acceleration a = (v*v)/s
                if (this.arrayPoints.length > 2) {
                    var S = hel_Distance(this.arrayPoints[0], this.arrayPoints[1]);
                    if (S != 0) {
                        this.aX = VELOCITY * VELOCITY / S;
                        this.aY = this.aX;
                    }
                }

            };

            /**
            * Scaling the path base on a scale
            */
            this.scalePath = function (widthScale, heightScale) {
                for (var i = 0; i < this.arrayPoints.length; i++) {
                    this.arrayPoints[i].X *= widthScale;
                    this.arrayPoints[i].Y *= heightScale;
                }
            }

            /**
             * update position and some variables
             */
            this.isCenterPoint = false;
            this.update = function (detalTime) {
                // Check if total item in arrayPoints less than 2 or not. 
                // If this.arrayPoints.length < 2 do not thing.
                if (this.arrayPoints.length < 2) {
                    return;
                }
                
                this.detalTime += detalTime;
                // check if it's time to be appearance
                if (!this.isMove) {
                    if (!this.isAppearance) {
                        if (this.detalTime > TIMEAPPEARANCE) {
                            this.isAppearance = true;
                        }
                    }
                    if (this.detalTime > TIMESTARTMOVE) {
                        this.isMove = true;
                        detalTime = 0;
                    }
                    return;
                }

                // Task update curPoint
                if (this.curS < this.limitS) {
                    if (this.detalTime < DELAYTIME) {
                        return;
                    }
                    var time = this.detalTime - DELAYTIME;
                    var velocity = 0;
                    var a = ACCELERATION;

                    velocity = this.Vo + (a * time);
                    var Vx = this.VectorVelocity.X * velocity;
                    var Vy = this.VectorVelocity.Y * velocity;

                    this.curPoint.X = this.beginPoint.X + Vx * time;
                    this.curPoint.Y = this.beginPoint.Y + Vy * time;
                    if (this.curPoint.X >= X_CHANGEBODY) {
                        this.isLeftBody = false;
                    }
                    else {
                        this.isLeftBody = true;
                    }
                    this.curS = hel_Distance(this.curPoint, this.beginPoint);
                } else {
                    // Check if current index is equal last item in arrrayPoints
                    if (this.curIndex === (this.arrayPoints.length - 1)) {
                        // Current index is the last item so the endPoint must be the begin item of arrayPoints
                        this.beginPoint.X = this.curPoint.X;
                        this.beginPoint.Y = this.curPoint.Y;
                        this.endPoint = this.arrayPoints[0];
                        this.curIndex = 0;

                    }
                    else {
                        this.beginPoint.X = this.curPoint.X;
                        this.beginPoint.Y = this.curPoint.Y;
                        this.endPoint = this.arrayPoints[this.curIndex + 1];
                        this.curIndex++;
                    }

                    // Vector velocity
                    this.VectorVelocity.X = this.endPoint.X - this.beginPoint.X;
                    this.VectorVelocity.Y = this.endPoint.Y - this.beginPoint.Y;
                    this.VectorVelocity.Y = this.VectorVelocity.Y / Math.abs(this.VectorVelocity.X);
                    this.VectorVelocity.X = this.VectorVelocity.X / Math.abs(this.VectorVelocity.X);

                    this.limitS = hel_Distance(this.beginPoint, this.endPoint);// Distance between beginPoint and endPoint
                    this.curS = 0; // Distance between curPoint and beginPoint
                    this.isCenterPoint = false;
                    this.detalTime = 0;
                }
                //document.getElementById('showInfo').innerText = "finish update";
            };

            /**
            * Render 
            */
            this.render = function () {
                if (!this.isAppearance)
                {
                    return;
                }
                var dragonflyDom = document.getElementById(this.dragonflyID);
                var dragonflyRightBodyDom = document.getElementById(this.dragonflyRightBodyID);
                var dragonflyLeftBodyDom = document.getElementById(this.dragonflyLeftBodyID);

                dragonflyDom.setAttribute("style", "visibility: visible");
                var stranslate = "translate(" + this.curPoint.X + "," + this.curPoint.Y
                + ")";                
                dragonflyDom.setAttribute('transform', stranslate);

                

                if (this.isLeftBody) {
                    dragonflyRightBodyDom.setAttribute("style", "visibility: hidden");
                    dragonflyLeftBodyDom.setAttribute("style", "visibility: visible");
                } else {
                    dragonflyRightBodyDom.setAttribute("style", "visibility: visible");
                    dragonflyLeftBodyDom.setAttribute("style", "visibility: hidden");
                }
            };

        }

        // Global variables
        var timer;
        var dragonfly1;
        var dragonfly2;
        var beginTime = 0;

        /**
        * Initialize dragonfly
        */
        function init() {
            var date = new Date();
            beginTime = date.getTime();
            dragonfly1 = new DragonflyObj(BrowseWidth, BrowseHeight, new Point(500, 600), 'gDragonfly01', 'fly1_left', 'fly1_right');
            dragonfly1.init();
            dragonfly2 = new DragonflyObj(BrowseWidth, BrowseHeight, new Point(100, 200), 'gDragonfly02', 'fly2_left', 'fly2_right');
            dragonfly2.init();
            timer = setInterval(doAnim, DELAY);            
        }

        /**
         * update animation for dragonflys
         */
        function doAnim() {


            var curTime = new Date().getTime();
            var detalTime = (curTime - beginTime) / 1000;
            beginTime = curTime;
            // update
            dragonfly1.update(detalTime);
            dragonfly2.update(detalTime);
            //render
            dragonfly1.render();
            dragonfly2.render();
        }

        function resize() {
            var browserW = window.innerWidth;
            var browerH = window.innerHeight;

            var widthScale = browserW / BrowseWidth;
            var heightScale = browerH / BrowseHeight;

            BrowseHeight = browerH;
            BrowseWidth = browserW;
            if (dragonfly1) {
                dragonfly1.scalePath(widthScale, heightScale);
            }
            if (dragonfly2) {
                dragonfly2.scalePath(widthScale, heightScale);
            }
        }

    </script>
</head>
<body onload="init(); doAnim();" onresize="resize()">
    <div>
        <p id="firstInfo" />
        <p id="showInfo" />
    </div>
    <div>
        <svg width="100%" height="100%">
            <!-- first dragonfly -->
            <g id="gDragonfly01" style="visibility: hidden" transform="translate(100, 300)">
                <!--dragonfly's wing-->
                <image id="wing1" xlink:href="images/image_349.png" width="95" height="53" x="-47" y="-27">
                    <animateTransform dur="0.01s" repeatCount="indefinite" additive="sum" attributeName="transform" type="rotate" values="0;10;-20" />
                    <animate attributeType="CSS" attributeName="opacity" from="1" to="0" dur="0.5s" repeatCount="indefinite" />
                </image>
                <!--Left dragonfly's body-->
                <image id="fly1_left" xlink:href="images/image_body_left.png" width="45" height="57" x="-33" y="-14"></image>
                <!--Right dragonfly's body-->
                <image id="fly1_right" xlink:href="images/image_body_right.png" width="45" height="57" x="-12" y="-15">
                    <animateTransform attributeName="transform" type="rotate" from="10" to="10" />
                </image>
                <!--use for animation of dragonfly-->
            </g>

            <!-- second dragonfly -->
            <g id="gDragonfly02" style="visibility: hidden" transform="translate(100, 300)">
                <!-- Left dragonfly's body -->
                <!--dragonfly's wing-->
                <image id="wing2" xlink:href="images/image_349.png" width="95" height="53" x="-47" y="-27">
                    <animateTransform dur="0.01s" repeatCount="indefinite" additive="sum" attributeName="transform" type="rotate" values="0;10;-20" />
                    <animate attributeType="CSS" attributeName="opacity" from="1" to="0" dur="0.5s" repeatCount="indefinite" />
                </image>
                <image id="fly2_left" xlink:href="images/image_body_left.png" width="45" height="57" x="-33" y="-14">
                </image>
                <image id="fly2_right"  xlink:href="images/image_body_right.png" width="45" height="57" x="-12" y="-15">
                    <animateTransform attributeName="transform" type="rotate" from="10" to="10" />
                </image>
                <!-- dragonfly's wing -->
                <!--use for animation of dragonfly -->
            </g>

        </svg>
    </div>
</body>
</html>
